<?php

class cartModel extends RPHP_Model
{

    //获取用户会员信息
    public function getMemberInfo()
    {

        $sql = "SELECT * FROM {$this->_prefix['primary']}member_account WHERE  `uid`=" . $this->_user['uid'];
        return $this->db->getrow($sql);

    }

    public function getDocs($docid)
    {
        if (is_array($docid)) {
            $where = " WHERE `docid` IN (" . implode(",", array_unique($docid)) . ")";
        } else {
            $where = " WHERE `docid`=" . intval($docid);
        }

        $sql = "SELECT `docid`,`filename`,`create_time` FROM {$this->_prefix['primary']}documents " . $where;
        $rs  = $this->sql($sql);
        if ($rs) {
            foreach ($rs as $r) {
                $doc[$r['docid']] = $this->c['doc_host'] . date("Ymd", $r['create_time']) . "/" . date("H", $r['create_time']) . "/" . date("i", $r['create_time']) . "/" . $r['filename'];

            }
            return $doc;
        } else {
            return false;
        }

    }

    //保存文档
    public function saveDocument($name, $filename, $filesize, $format, $create_time, $imgwh)
    {

        $sql = "INSERT INTO {$this->_prefix['primary']}documents
        (`shopid`,`name`,`filename`,`filesize`,`format`,`create_time`,`imgwh`) VALUES
        (" . $this->_user['shopid'] . ",'" . $name . "','" . $filename . "'," . $filesize . ",'" . $format . "'," . $create_time . ",'" . $imgwh . "')";

        $docid = $this->sql($sql);
        return $docid;
    }

    //获取购物车数据
    public function getCart($getdocs = true, $cart_ids = false)
    {
        if ($cart_ids) {

            $tsql = " AND `id` IN (" . implode(",", array_unique($cart_ids)) . ")";
        }

        $sql  = "SELECT * FROM {$this->_prefix['primary']}goods_cart WHERE `uid`=" . $this->_user['uid'] . $tsql . " group by `goods_id`,`stock_id` ORDER BY `id` DESC";
        $data = $this->sql($sql);
        if ($data) {

            foreach ($data as $r) {

                if ($r['goods_id'] > 0) {
                    $goods_ids[]    = $r['goods_id'];
                    $cart[$r['id']] = $r;
                }

            }

            //获取商品信息
            $sql   = "SELECT * FROM {$this->_prefix['primary']}goods_data WHERE `goods_id` IN (" . implode(",", array_unique($goods_ids)) . ") AND `is_on_sale`=1 AND `is_delete`=0";
            $goods = $this->sql($sql);

            if ($goods) {
                $is_free_shipping = 1;

                $not_free = 0;

                foreach ($goods as $k => $r) {

                    $goods_data[$r['goods_id']] = $r;

                    if ($r['thumb_docid'] > 0) {
                        $docid[] = $r['thumb_docid'];
                    }

                    if ($r['pic_docid'] > 0) {
                        $docid[] = $r['pic_docid'];
                    }

                    if ($r['limit_number'] > 0) {
                        $limit_goods_id[] = $r['goods_id'];
                    }

                    if ($r['declaration'] > 0) {
                        $declaration = $r['declaration'];

                    }
                    if ($r['is_free_shipping'] == 1) {

                    } else {
                        $not_free += 1;
                    }

                    $new_goods_ids[] = $r['goods_id'];

                    if ($not_free > 0) {
                        $is_free_shipping = 0;
                    }

                }

                /*
                // 获取限购信息
                if($limit_goods_id){
                $bought = $this->getLimitBought($limit_goods_id,true);
                }
                 */

                //获取商品库存
                if ($new_goods_ids) {

                    $sql  = "SELECT `goods_id`,`number` FROM {$this->_prefix['primary']}goods_stock WHERE `goods_id` IN(" . implode(",", $new_goods_ids) . ")";
                    $data = $this->sql($sql);
                    if ($data) {

                        foreach ($data as $v) {
                            $number[$v['goods_id']] = $v['number'];
                        }

                        if ($number) {
                            foreach ($cart as $k => $v) {
                                $cart[$k]['stocknumber'] = $number[$v['goods_id']];
                                if ($v['stock_id']) {
                                    $cart[$k]['stocknumber'] = $this->table('goods_affi_spec')->findOneBySql('`stock_id`='.$v['stock_id'],'goods_number');
                                }
                            }
                        }
                    }
                }

                if ($docid && $getdocs) {
                    $docs = $this->getDocs($docid);
                }

                foreach ($cart as $k => $val) {                    
                    $cart[$k]['express_setting'] = $goods_data[$val['goods_id']]['express_setting'];
                    $cart[$k]['attr_str'] = "";
                    if ($val['stock_id']) {
                        $shop_price2 = $this->table('goods_affi_spec')->findOneBySql('`stock_id`='.$val['stock_id'],'goods_price');
                        $cart[$k]['shop_price'] = $shop_price2;
                        $goods_data[$val['goods_id']]['shop_price'] = $shop_price2;
                        $cart[$k]['attr_str'] = $this->table('goods_affi_spec')->findOneBySql('`stock_id`='.$val['stock_id'],'spec_name');
                    }else{
                       $cart[$k]['shop_price']      = $goods_data[$val['goods_id']]['shop_price']; 
                    }
                    

                }

            }
        }
// var_dump($cart);exit;
        if ($goods_data) {
            return array(
                'cart'             => $cart,
                'goods'            => $goods_data,
                'docs'             => $docs,
                'declaration'      => $declaration,
                'is_free_shipping' => $is_free_shipping,
            );
        }

    }

    //添加到购物车
    public function addToCart($da)
    {
        $code = 404;

        $goods_id     = intval($da['goods_id']);
        $goods_number = intval($da['goods_number']);
        $stock_id = intval($da['stock_id']);

        $shopid       = 1;
        //默认当前 yxs
        if ($shopid <= 0) {
            $shopid = $this->_shop['shopid'];
        }
        if ($goods_number < 1) {
            $goods_number = 1;
        }

        if ($goods_id > 0) {
            $goods_spec = $this->table("goods_affi_spec")->findAllBySql("`goods_id`=".$goods_id);

            if ( count($goods_spec) > 0 ) {
                if (!$stock_id) {
                    $code = 990;
                    return array(
                        'code'    => $code,
                        // 'cartnum' => $cartnum,
                    );
                }else{
                    //查询规格库存
                    foreach ($goods_spec as $key => $value) {
                        if ($stock_id == $value['stock_id']) {
                            $goodsnumber = $value['goods_number'];
                        }
                        
                    }
                }
            }else{
                //查询本库存
                $sql         = "SELECT `number` FROM {$this->_prefix['primary']}goods_stock WHERE `goods_id` =" . $goods_id;
                $goodsnumber = $this->db->getone($sql);
            }
            

            //$goodsnumber库存数量
            if ($goodsnumber > 0) {
                $sql   = "SELECT `goods_id`,`limit_number` FROM {$this->_prefix['primary']}goods_data WHERE `goods_id`=" . $goods_id . " AND `is_on_sale`=1 AND `is_delete`=0";
                $goods = $this->db->getrow($sql);
                if ($goods['goods_id'] > 0) {
                    if ($goodsnumber <= 0) {
                        $code = 781;
                    }
                    //商品已售空
                    elseif ($goodsnumber >= $goods_number) {

                        //库存数量，最大购买数
                        $max_number = $goodsnumber;

                        if ($max_number > 0 && $goods_number <= $max_number && $goods_number > 0) {

                            //获取已经存在的相同商品
                            $sql    = "SELECT `id`,`number` FROM {$this->_prefix['primary']}goods_cart WHERE `uid`=" . $this->_user['uid'] . " AND `goods_id`=" . $goods_id . " AND `stock_id`=" . $stock_id;
                            $exists = $this->db->getrow($sql);

                            if($exists){
                                $goods_number += $exists['number'];
                            }
                            //限购
                            $done =$this->isPurchasingGoods($goods_id,$goods_number);
                            if($done['code'] !=200){
                                return array('code'=>785);

                            }


                            if ($exists) {
                                if ($exists['number'] <= $goodsnumber) {
                                    if ($exists['number'] + $goods_number > $goodsnumber) {
                                        $number = $goodsnumber;
                                    } else if ($exists['number'] + $goods_number <= $goodsnumber) {
                                        $number = $exists['number'] + $goods_number;
                                    }
                                } else {
                                    $number = $goodsnumber;
                                }

                                if ($number > 0) {

                                    if ($number > $max_number) {
                                        $number = $max_number;
                                    }

                                    $sql  = "UPDATE {$this->_prefix['primary']}goods_cart SET `number`=" . $number . " WHERE `id`=" . $exists['id'] . " AND `uid`=" . $this->_user['uid'];
                                    $rcid = $this->sql($sql);

                                    if ($rcid > 0) {
                                        $_odo = true;
                                    } else {
                                        $_odo = false;
                                    }
                                }

                            } else {

                                if ($goods_number > $max_number) {
                                    $goods_number = $max_number;
                                }

                                $sql  = "INSERT INTO {$this->_prefix['primary']}goods_cart (`uid`,`goods_id`,`number`,`create_time`,`stock_id`) VALUES (" . $this->_user['uid'] . "," . $goods_id . "," . $goods_number . "," . $_SERVER['REQUEST_TIME'] . "," . $stock_id . ")";
                                $rcid = $this->sql($sql);

                                if ($rcid > 0) {
                                    $_odo = true;
                                } else {
                                    $_odo = false;
                                }
                            }
                            if ($_odo) {
                                $code = 200;
                            } else {
                                $code = 403;
                            }

                        } else {
                            $code = 782;
                        }

                    } else {
                        $code = 780;
                    }
                    //商品库存不足
                } else {
                    $code = 784;
                }
                //商品不存在
            } else {
                $code = 783;
            }
            //没有商品库存数量
        }

        // 查询购物车商品数量
        $sql     = "SELECT SUM(cr.`number`) AS `cnt` FROM {$this->_prefix['primary']}goods_cart cr INNER JOIN {$this->_prefix['primary']}goods_data gd ON cr.`uid`=" . $this->_user['uid'] . " AND gd.`goods_id` = cr.`goods_id` AND gd.`is_on_sale`=1 AND gd.`is_delete`=0";
        $cartnum = $this->db->getone($sql);
        if ($cartnum > 99) {
            $cartnum = 99;
        } elseif (!$cartnum) {
            $cartnum = 0;
        }

        return array(
            'code'    => $code,
            'cartnum' => $cartnum,
        );
    }

    //从购物车删除
    public function removeCart($cartid)
    {

        $code = 404;
        if ($cartid > 0) {

            $sql = "DELETE FROM {$this->_prefix['primary']}goods_cart WHERE `id`=" . $cartid . " AND `uid`=" . $this->_user['uid'];
            $rc  = $this->sql($sql);
            if ($rc > 0) {
                $code = 200;
            } else {
                $code = 403;
            }

        }

        return $code;

    }

    //更新商品数量
    public function updateCart($cartid, $goods_number)
    {

        $code = 404;

        if ($cartid > 0 && $goods_number > 0) {
            // 获取购物车数据
            $sql  = "SELECT `id`,`goods_id`,`number`,`stock_id` FROM {$this->_prefix['primary']}goods_cart WHERE `id`=" . $cartid . " AND `uid`=" . $this->_user['uid'];
            $cart = $this->db->getrow($sql);
            if ($cart) {
                if ($cart['stock_id']) {
                    $goods_stock_number = $this->table('goods_affi_spec')->findOneBySql('`stock_id`='.$cart['stock_id'],'goods_number');
                }else{
                    // 获取商品可用库存
                    $sql                = "SELECT `number` FROM {$this->_prefix['primary']}goods_stock WHERE `goods_id` =" . $cart['goods_id'];
                    $goods_stock_number = $this->db->getone($sql);
                }
                
                if ($goods_stock_number >= $goods_number) {
                    $done =  $this->isPurchasingGoods( $cart['goods_id'],$goods_number);
                    if($done['code'] !=200){
                        return  901;

                    }
                    $sql = "UPDATE {$this->_prefix['primary']}goods_cart SET `number`=" . $goods_number . " WHERE `id`=" . $cart['id'] . " AND `uid`=" . $this->_user['uid'];
                    $rc  = $this->sql($sql);
                    if ($rc > 0) {

                        $code = 200;

                    } else {
                        $code = 403;
                    }
                }

            }

        }

        return $code;

    }

    //是否存在限购商品
    public function isPurchasingGoods($goods_id = 0,$g_num=0)
    {

        if ($goods_id) {

            $order_ids   = "";
            $is_exper    = true;
            $sql    = "SELECT `order_id` FROM {$this->_prefix['primary']}order_info WHERE uid=" . $this->_user['uid'] . " AND `pay_status` IN (2,6) AND `shipping_status` NOT IN (7,8)";
            $orders = $this->sql($sql);

            foreach ($orders as $key => $val) {

                $order_ids .= empty($order_ids) ? $val['order_id'] : ',' . $val['order_id'];
            }

            $order_idss = trim($order_ids); //用户购买的订单



            $sql         = "SELECT `purchasing_num`,`goods_id` FROM {$this->_prefix['primary']}goods_data WHERE goods_id =" . $goods_id;
            $goodsDetail = $this->db->getrow($sql);
            //print_r($goodsDetail['purchasing_num']."==".$g_num);die;
            if ($goodsDetail['purchasing_num'] > 0) {
                if ($g_num > $goodsDetail['purchasing_num']) {
                    //购买数量大于限购数量
                    $is_exper    = false;

                } else {

                    if ($order_idss) {
                        $number = 0;
                        $sql    = "SELECT `goods_number`,`goods_id` FROM {$this->_prefix['primary']}order_goods WHERE order_id IN (" . $order_idss . ") AND goods_id =" . $goodsDetail['goods_id'];
                        $orders = $this->sql($sql);

                        foreach ($orders as $k => $v) {

                            $number += $v['goods_number'];
                        }
                        if (($g_num + $number) > $goodsDetail['purchasing_num']) {

                            $is_exper    = false;

                        }
                    }
                }
            }



        }

        if($is_exper){
            $arr['code'] =200;

        }
        $arr['purchasing_num'] =$goodsDetail['purchasing_num'];

        return $arr;
    }


    //结算页面是否存在限购商品
    public function purchasingGoods($cartidss)
    {
        $arr         = array();
        $cartids     = trim($cartidss);
        if (!empty($cartids)) {

            $goods_ids   = '';
            $order_ids   = "";
            $is_exper    = true;
            $sql         = "SELECT `goods_id`,`number` FROM {$this->_prefix['primary']}goods_cart WHERE id IN (" . $cartids . ")";
            $cartsList   = $this->sql($sql);

            $sql    = "SELECT `order_id` FROM {$this->_prefix['primary']}order_info WHERE uid=" . $this->_user['uid'] . " AND `pay_status` IN (2,6) AND `shipping_status` NOT IN (7,8)";
            $orders = $this->sql($sql);

            foreach ($orders as $key => $val) {

                $order_ids .= empty($order_ids) ? $val['order_id'] : ',' . $val['order_id'];
            }

            $order_idss = trim($order_ids); //用户购买的订单

            foreach ($cartsList as $key => $val) {

                $sql         = "SELECT `purchasing_num`,`goods_id` FROM {$this->_prefix['primary']}goods_data WHERE goods_id =" . $val['goods_id'];
                $goodsDetail = $this->db->getrow($sql);
                //print_r($goodsDetail['purchasing_num']."==".$val['number']);die;
                if ($goodsDetail['purchasing_num'] > 0) {
                    $arr['type'] = false;
                    if ($val['number'] > $goodsDetail['purchasing_num']) {
//购买数量大于限购数量
                        $is_exper    = false;

                    } else {

                        if ($order_idss) {
                            $number = 0;
                            $sql    = "SELECT `goods_number`,`goods_id` FROM {$this->_prefix['primary']}order_goods WHERE order_id IN (" . $order_idss . ") AND goods_id =" . $goodsDetail['goods_id'];
                            $orders = $this->sql($sql);

                            foreach ($orders as $k => $v) {

                                $number += $v['goods_number'];
                            }

                            if (($val['number'] + $number) > $goodsDetail['purchasing_num']) {

                                $is_exper    = false;

                            }
                        }
                    }
                }
            }

            if ($is_exper) {
                $arr['code'] = 200;
            }else{
                $arr['code'] = 901;
                $arr['msg']  = "商品已超出了限购数量";

            }

        } else {
            $arr['code'] = 901;
            $arr['msg']  = "您未选择商品，请选择商品购买！";

        }

        return $arr;
    }

    //获取收货地址
    public function getAddress($uid, $id = 0, $limit = false)
    {

        if ($id > 0) {
            $tsql = " AND `id`=" . $id;
        }

        if ($limit) {
            $limit_str = ' LIMIT 1';
        }

        $sql = "SELECT * FROM {$this->_prefix['primary']}member_address WHERE `uid`=" . $this->_user['uid'] . $tsql . " ORDER BY `is_default` DESC" . $limit_str;
        if ($id > 0 || $limit) {
            $data = $this->db->getrow($sql);
            if ($data) {
                if ($data['province_id'] > 0) {
                    $region_id[] = $data['province_id'];
                }

                if ($data['city_id'] > 0) {
                    $region_id[] = $data['city_id'];
                }

                if ($data['county_id'] > 0) {
                    $region_id[] = $data['county_id'];
                }

                if ($region_id) {
                    $sql         = "SELECT `region_id`,`region_name` FROM {$this->_prefix['primary']}region WHERE `region_id` IN (" . implode(",", array_unique($region_id)) . ")";
                    $region_data = $this->sql($sql);
                    if ($region_data) {
                        foreach ($region_data as $r) {
                            $region[$r['region_id']] = $r['region_name'];
                        }

                        if ($data['province_id'] > 0) {
                            $data['province_name'] = $region[$data['province_id']];
                        }

                        if ($data['city_id'] > 0) {
                            $data['city_name'] = $region[$data['city_id']];
                        }

                        if ($data['county_id'] > 0) {
                            $data['county_name'] = $region[$data['county_id']];
                        }
                    }
                }
            }
        } else {
            $data = $this->sql($sql);
            if ($data) {
                foreach ($data as $r) {
                    if ($r['province_id'] > 0) {
                        $region_id[] = $r['province_id'];
                    }

                    if ($r['city_id'] > 0) {
                        $region_id[] = $r['city_id'];
                    }

                    if ($r['county_id'] > 0) {
                        $region_id[] = $r['county_id'];
                    }

                }

                if ($region_id) {
                    $sql         = "SELECT `region_id`,`region_name` FROM {$this->_prefix['primary']}region WHERE `region_id` IN (" . implode(",", array_unique($region_id)) . ")";
                    $region_data = $this->sql($sql);
                    if ($region_data) {
                        foreach ($region_data as $r) {
                            $region[$r['region_id']] = $r['region_name'];
                        }
                    }

                    foreach ($data as $k => $r) {
                        if ($r['province_id'] > 0) {
                            $data[$k]['province_name'] = $region[$r['province_id']];
                        }

                        if ($r['city_id'] > 0) {
                            $data[$k]['city_name'] = $region[$r['city_id']];
                        }

                        if ($r['county_id'] > 0) {
                            $data[$k]['county_name'] = $region[$r['county_id']];
                        }

                    }
                }
            }
        }
        return $data;
    }

    // 获取区域信息
    public function getRegion()
    {
        $sql = "SELECT `region_id`,`region_name`,`parent_id` FROM {$this->_prefix['primary']}region ORDER BY `parent_id` ASC,`region_id` ASC";

        $data = $this->sql($sql);
        if ($data) {
            foreach ($data as $r) {
                $new[$r['parent_id']][$r['region_id']] = $r;
            }
            return $new;
        }

    }

    // 制作订单编号
    public function makeOrderSn()
    {
        $sql           = "SELECT `order_id` FROM {$this->_prefix['primary']}order_info ORDER BY `order_id` DESC LIMIT 1";
        $prev_order_id = $this->db->getone($sql);
        if (!$prev_order_id || $prev_order_id < 1) {
            $prev_order_id = 1;
        }

        $order_sn = date("Ymd") . rand(100, 999) . ($prev_order_id + 1);

        return $order_sn;
    }

    //保存订单
    public function saveOrder($da)
    {

        $code       = 900;
        $uid        = intval($this->_user['uid']);
        $cartid_arr = explode(",", $da['cartid']);
        $dis_gold   = intval($da['dis_gold']) == 1 ? 1 : 0;
        $dis_coupon = intval($da['dis_coupon']) == 1 ? 1 : 0;
        $coupon_id  = intval($da['coupon_id']);
        $donext     = true;
        if (is_array($cartid_arr)) {

            foreach ($cartid_arr as $r) {
                $r = intval($r);
                if ($r > 0) {
                    $cartid[$r] = $r;
                }
            }
        }

        if ($da && is_array($cartid) && $uid > 0) {

            $cart = $this->getCart(false, $cartid);

            // 订单拆分
            if ($cart['cart'] && $cart['goods']) {

                //地址相关信息
                $address_id = intval($da['address_id']);
                if ($address_id > 0) {
                    $addr = $this->getAddress($uid, $address_id);
                }

                $order_field['goods_amount'] = $order_field['order_amount'] = $order_field['supply_amount'] = $order_field['purchase_amount'] = $order_field['shipping_fee'] = $order_field['pay_fee'] = 0;

                foreach ($cart['cart'] as $key => $val) {

                    if($val['express_setting']!="")
                    {
                        $express_setting = json_decode($val['express_setting'],true);

                        if($express_setting['no_sale'][$addr['province_id']])
                        {
                            unset($cart['cart'][$key]);
                        }
                        elseif($express_setting['extra_money'][$addr['province_id']] > 0)
                        {
                            $express_money += $val['number'] * $express_setting['extra_money'][$addr['province_id']];
                        }
                    }

                }

                if (empty($cart['cart'])) {
                    // 订单有误
                    $code   = 852;
                    $donext = false;
                }

                $order_field['shipping_fee'] = 8;

                if ($cart['is_free_shipping']) {

                    $order_field['shipping_fee'] = 0;
                }
                
                $order_field['shipping_fee'] += $express_money > 0 ? $express_money : 0;
                //订单编号
                $order_sn                = $this->makeOrderSn();
                $order_field['order_sn'] = $order_sn;
                $order_field['uid']      = $uid;
                $order_field['add_time'] = $_SERVER['REQUEST_TIME'];
                $order_field['remark']   = addslashes(stripslashes(trim($da['remark'])));
                // 支付类型微信公众号
                $order_field['transaction_type'] = 1;

                if ($addr) {

                    $order_field['idnum']       = addslashes($addr['idnum']);
                    $order_field['consignee']   = addslashes($addr['realname']);
                    $order_field['mobile']      = addslashes($addr['mobile']);
                    $order_field['address']     = addslashes($addr['address']);
                    $order_field['province_id'] = $addr['province_id'];
                    $order_field['city_id']     = $addr['city_id'];
                    $order_field['county_id']   = $addr['county_id'];

                    // 检查是否需要报关身份证号码
                    foreach ($cart['goods'] as $r) {

                        if ($r['declaration'] == 1) {

                            if ($addr['idnum'] == "" || strlen($addr['idnum']) != 18) {
                                // 收货人需要填写身份证号码
                                $code   = 851;
                                $donext = false;
                            }

                        }

                    }
                } else {
                    // 收货人信息不完整
                    $code   = 850;
                    $donext = false;
                }

                if ($donext) {
                    // 计算价格
                    foreach ($cart['cart'] as $cart_id => $v) {

                        if ($cart['goods'][$v['goods_id']] && $v['number'] <= $v['stocknumber']) {

                            $goods = $cart['goods'][$v['goods_id']];

                            if ($goods['ximi_price'] > 0) {
                                $order_field['ximi_fee'] += $v['number'] * $goods['ximi_price'];
                            } elseif ($v['shop_price'] > 0) {
                                $order_field['goods_amount'] += $v['number'] * $v['shop_price'];

                                if ($goods['can_use_gold'] == 1) {
                                    $gold_total += $v['number'] * $v['shop_price'];
                                }
                            }

                            $order_field['supply_amount'] += $v['number'] * $goods['supply_price'];
                            $order_field['purchase_amount'] += $v['number'] * $goods['purchase_price'];

                            if ($goods['coupon_price'] > 0) {
                                $coupon_total += $v['number'] * $goods['coupon_price'];
                            }

                        }
                    }

                    if ($order_field['goods_amount'] > 0 || $order_field['ximi_fee'] > 0) {

                        //开始事务
                        $this->db->begin();
                        $commit      = false;
                        $use_coupon  = false;
                        $code        = 403;
                        $donext      = true;
                        $member_data = $this->getMemberInfo();

                        // 订单总金额

                        $order_field['order_amount'] = $order_field['goods_amount'] + $order_field['shipping_fee'];

                        // 应付款金额
                        $pay_fee = $order_field['order_amount'];

                        if ($coupon_id > 0) {

                            $coupons = $this->getCoupon($coupon_id);

                            if ($coupons[$coupon_id] && $order_field['goods_amount'] >= $coupons[$coupon_id]['need_money']) {
                                $order_field['discount_fee'] = $coupons[$coupon_id]['money'];
                                $pay_fee -= $order_field['discount_fee'];
                                $use_coupon = true;
                            }
                        }

                        //相关抵扣计算
                        $balance = $this->getBalance();

                        if ($order_field['ximi_fee'] > 0) {
                            if ($balance['ximi_money'] >= $order_field['ximi_fee']) {

                            } else {
                                $donext = false;
                                $code   = 865;
                            }
                        }

                        //代金券抵扣
                        if ($dis_coupon == 1 && $coupon_total > 0 && $balance['coupon'] > 0 && $pay_fee > 0) {

                            if ($balance['coupon'] >= $coupon_total) {
                                $pay_fee -= $coupon_total;
                                $order_field['coupon_fee'] = $coupon_total;
                            } else {

                                if ($balance['coupon'] >= $pay_fee) {
                                    $order_field['coupon_fee'] = $pay_fee;
                                    $pay_fee                   = 0;
                                } else {
                                    $pay_fee -= $balance['coupon'];
                                    $order_field['coupon_fee'] = $balance['coupon'];
                                }

                            }

                        }

                        //金花抵扣
                        if ($dis_gold == 1 && $gold_total > 0 && $balance['gold_money'] > 0 && $pay_fee > 0) {

                            if ($balance['gold_money'] >= $gold_total) {

                                if ($pay_fee < $gold_total) {
                                    $order_field['gold_fee'] = $pay_fee;
                                    $pay_fee                 = 0;
                                } else {
                                    $pay_fee -= $gold_total;
                                    $order_field['gold_fee'] = $gold_total;
                                }

                            } else {

                                if ($balance['gold_money'] >= $pay_fee) {
                                    $order_field['gold_fee'] = $pay_fee;
                                    $pay_fee                 = 0;
                                } else {
                                    $pay_fee -= $balance['gold_money'];
                                    $order_field['gold_fee'] = $balance['gold_money'];
                                }

                            }

                        }

                        if ($pay_fee <= 0) {

                            $pay_fee                     = 0;
                            $order_field['pay_status']   = 2;
                            $order_field['order_status'] = 1;
                            $order_field['pay_time']     = time();

                        }

                        $order_field['pay_fee']       = number_format($pay_fee, 2, ".", "");
                        $order_field['pay_total_fee'] = $pay_total_fee = $order_field['pay_fee'] * 100;

                        //上级ID
                        if ($member_data['pid'] > 0) {
                            $order_field['pid'] = $member_data['pid'];

                        }

                        /*print_r($order_field);
                        die();*/

                        if ($donext) {
                            //组织订单SQL
                            $sql = "INSERT INTO {$this->_prefix['primary']}order_info ";
                            foreach ($order_field as $k => $r) {
                                $field[] = "`" . $k . "`";
                                $value[] = "'" . $r . "'";
                            }

                            $sql .= "(" . implode(",", $field) . ") VALUES (" . implode(",", $value) . ")";

                            $order_id = $this->sql($sql);
                            //echo $sql;die;
                            //如果插入订单成功
                            if ($order_id > 0) {

                                $commit = true;

                                // 更新赠送优惠券的使用状态
                                if ($commit && $use_coupon && $coupon_id > 0) {

                                    $commit = false;
                                    $sql    = "UPDATE {$this->_prefix['primary']}discount_coupon SET `order_id`=" . $order_id . ",`status`=1,`used_time`=" . $_SERVER['REQUEST_TIME'] . " WHERE `coupon_id`=" . $coupon_id . " AND `uid`=" . $this->_user['uid'];
                                    $upcc   = $this->sql($sql);
                                    if ($upcc > 0) {
                                        $commit = true;
                                    } else {
                                        $code = 858;
                                    }
                                }

                                //使用金花抵扣
                                if ($commit && $order_field['gold_fee'] > 0 && $balance) {

                                    $commit = false;

                                    $sql  = "UPDATE {$this->_prefix['primary']}finance_balance SET `gold_money`=`gold_money`-" . $order_field['gold_fee'] . ",`update_time`=" . $_SERVER['REQUEST_TIME'] . ",`random_num`=" . rand(100000, 999999) . " WHERE `uid`=" . $balance['uid'];
                                    $upid = $this->sql($sql);
                                    if ($upid) {
                                        $detail_note = "订单号" . $order_sn . "使用金花抵扣";
                                        $event       = 12;
                                        $sql         = "INSERT INTO {$this->_prefix['primary']}finance_detail (`uid`,`event`,`cmoney`,`money`,`create_time`,`note`,`dataid`,`table_name`) VALUES (" . $balance['uid'] . "," . $event . "," . $order_field['gold_fee'] . "," . ($balance['gold_money'] - $order_field['gold_fee']) . "," . $_SERVER['REQUEST_TIME'] . ",'" . $detail_note . "'," . $order_id . ",'order_info')";
                                        $detail_id   = $this->sql($sql);
                                        if ($detail_id) {
                                            $commit = true;

                                        } else {

                                            $code = 862;
                                        }

                                    } else {

                                        $code = 861;
                                    }

                                }

                                //使用代金券抵扣
                                if ($commit && $order_field['coupon_fee'] > 0 && $balance) {

                                    $commit = false;

                                    $sql  = "UPDATE {$this->_prefix['primary']}finance_balance SET `coupon`=`coupon`-" . $order_field['coupon_fee'] . ",`update_time`=" . $_SERVER['REQUEST_TIME'] . ",`random_num`=" . rand(100000, 999999) . " WHERE `uid`=" . $balance['uid'];
                                    $upid = $this->sql($sql);
                                    if ($upid) {
                                        $detail_note = "订单号" . $order_sn . ",使用代金券抵扣";
                                        $event       = 13;
                                        $sql         = "INSERT INTO {$this->_prefix['primary']}finance_detail (`uid`,`event`,`cmoney`,`money`,`create_time`,`note`,`dataid`,`table_name`) VALUES (" . $balance['uid'] . "," . $event . "," . $order_field['coupon_fee'] . "," . ($balance['coupon'] - $order_field['coupon_fee']) . "," . $_SERVER['REQUEST_TIME'] . ",'" . $detail_note . "'," . $order_id . ",'order_info')";
                                        $detail_id   = $this->sql($sql);
                                        if ($detail_id) {
                                            $commit = true;

                                        } else {

                                            $code = 864;
                                        }

                                    } else {

                                        $code = 863;
                                    }

                                }

                                //使用硒米消费
                                if ($commit && $order_field['ximi_fee'] > 0 && $balance) {
                                    $commit = false;

                                    $sql  = "UPDATE {$this->_prefix['primary']}finance_balance SET `ximi_money`=`ximi_money`-" . $order_field['ximi_fee'] . ",`update_time`=" . $_SERVER['REQUEST_TIME'] . ",`random_num`=" . rand(100000, 999999) . " WHERE `uid`=" . $balance['uid'];
                                    $upid = $this->sql($sql);
                                    if ($upid) {
                                        $detail_note = "订单号" . $order_sn . ",使用硒米消费";
                                        $event       = 14;
                                        $sql         = "INSERT INTO {$this->_prefix['primary']}finance_detail (`uid`,`event`,`cmoney`,`money`,`create_time`,`note`,`dataid`,`table_name`) VALUES (" . $balance['uid'] . "," . $event . "," . $order_field['ximi_fee'] . "," . ($balance['ximi_money'] - $order_field['ximi_fee']) . "," . $_SERVER['REQUEST_TIME'] . ",'" . $detail_note . "'," . $order_id . ",'order_info')";
                                        $detail_id   = $this->sql($sql);
                                        if ($detail_id) {
                                            $commit = true;

                                        } else {

                                            $code = 864;
                                        }

                                    } else {

                                        $code = 863;
                                    }

                                }

                                if ($commit) {
                                    foreach ($cart['cart'] as $cart_id => $v) {

                                        if ($cart['goods'][$v['goods_id']] && $v['number'] <= $v['stocknumber'] && $commit) {

                                            $commit = false;

                                            $goods = $cart['goods'][$v['goods_id']];

                                            $sql = "INSERT INTO {$this->_prefix['primary']}order_goods (
                                            `order_id`,
                                            `goods_id`,
                                            `supplierid`,
                                            `goods_name`,
                                            `goods_sn`,
                                            `goods_barcode`,
                                            `goods_number`,
                                            `market_price`,
                                            `goods_price`,
                                            `purchase_price`,
                                            `price_me`,
                                            `price_level1`,
                                            `price_level2`,
                                            `goods_type`,
                                            `ximi_price`,
                                            `coupon_price`,
                                            `give_ticket`,
                                            `give_coupon`,
                                            `commission_setting`,
                                            `upgrade_goods`,
                                            `can_not_reback`,
                                            `maker_level`,
                                            `express_setting`,
                                            `add_time`,
                                            `stock_id`
                                            ) VALUES (
                                            " . $order_id . ",
                                            " . $goods['goods_id'] . ",
                                            " . $goods['supplierid'] . ",
                                            '" . addslashes($goods['goods_name']) . "',
                                            '" . $goods['goods_sn'] . "',
                                            '" . $goods['goods_barcode'] . "',
                                            " . $v['number'] . ",
                                            " . $goods['market_price'] . ",
                                            " . $v['shop_price'] . ",
                                            " . $goods['purchase_price'] . ",
                                            " . $goods['price_me'] . ",
                                            " . $goods['price_level1'] . ",
                                            " . $goods['price_level2'] . ",
                                            " . $goods['goods_type'] . ",
                                            " . $goods['ximi_price'] . ",
                                            " . $goods['coupon_price'] . ",
                                            " . $goods['give_ticket'] . ",
                                            " . $goods['give_coupon'] . ",
                                            '" . $goods['commission_setting'] . "',
                                            " . $goods['upgrade_goods'] . ",
                                            " . $goods['can_not_reback'] . ",
                                            " . $goods['maker_level'] . ",
                                            '" . $goods['express_setting'] . "',
                                            " . $_SERVER['REQUEST_TIME'] . ",
                                            " . $v['stock_id'] . "
                                            )";

                                            $rec_id = $this->sql($sql);

                                            if ($rec_id > 0) {
                                                //删除购物车中的商品
                                                $sql = "DELETE FROM {$this->_prefix['primary']}goods_cart WHERE `id`=" . $cart_id . " AND `uid`=" . $uid;
                                                $this->sql($sql);

                                                //更新商品库存
                                                $sql     = "UPDATE {$this->_prefix['primary']}goods_stock SET `number`=`number`-" . $v['number'] . " WHERE `goods_id`=" . $goods['goods_id'] . " AND `number`>=" . $v['number'];
                                                $rcstock = $this->sql($sql);
                                                if ($rcstock > 0) {
                                                    if ($v['stock_id'] > 0) {
                                                        $upstocknumber = $this->table('goods_affi_spec')->updateBySql("`goods_number`=`goods_number`-".$v['number'],"`stock_id`=".$v['stock_id']);

                                                        if ($upstocknumber > 0) {
                                                            // 更新商品销售数量
                                                            $sql = "UPDATE {$this->_prefix['primary']}goods_data SET `sales_count`=`sales_count`+" . $v['number'] . " WHERE `goods_id`=" . $goods['goods_id'];
                                                            $rcg = $this->sql($sql);
                                                            if ($rcg > 0) {

                                                                $commit = true;

                                                            } else {

                                                                $code = 857;
                                                            }
                                                        }else{
                                                            $code = 856;
                                                        }
                                                       
                                                    }else{
                                                        // 更新商品销售数量
                                                        $sql = "UPDATE {$this->_prefix['primary']}goods_data SET `sales_count`=`sales_count`+" . $v['number'] . " WHERE `goods_id`=" . $goods['goods_id'];
                                                        $rcg = $this->sql($sql);
                                                        if ($rcg > 0) {

                                                            $commit = true;

                                                        } else {

                                                            $code = 857;
                                                        }
                                                    }
                                                    

                                                } else {
                                                    $code = 856;

                                                }

                                            } else {
                                                $code = 855;
                                            }

                                        }
                                    }
                                }

                            } else {
                                $code = 853;
                            }
                        }

                        //执行COMMIT
                        if ($commit) {
                            $code = 200;
                            $this->db->commit();

                        } else {
                            $this->db->rollback();
                        }

                    } else {
                        $code = 852;
                    }
                }

            }
        }
        return array(
            'code'          => $code,
            'order_id'      => $order_id,
            'order_sn'      => $order_sn,
            'pay_fee'       => $pay_fee,
            'pay_total_fee' => $pay_total_fee,
            'pay_status'    => $order_field['pay_status'],
        );
    }

    //保存收货地址
    public function saveAddress($da)
    {
        $code = 900;

        $realname   = addslashes(htmlspecialchars(trim($da['realname'])));
        $mobile     = addslashes(htmlspecialchars(trim($da['mobile'])));
        $region     = addslashes(htmlspecialchars(trim($da['region'])));
        $address    = addslashes(htmlspecialchars(trim($da['address'])));
        $is_default = intval($da['is_default']);

        if ($realname != "" && $mobile != "" && $region != "" && $address != "") {
            if (preg_match("/^(13|14|15|16|17|18|19)([0-9]{9})$/", $mobile)) {
                $region = explode(",", $region);

                $province_id = intval($region[0]);
                $city_id     = intval($region[1]);
                $county_id   = intval($region[2]);
                $idnum       = addslashes(stripcslashes(trim($da['idnum'])));

                if ($province_id > 0 && $city_id > 0) {
                    $sql = "INSERT INTO {$this->_prefix['primary']}member_address (`uid`,`realname`,`mobile`,`province_id`,`city_id`,`county_id`,`address`,`is_default`,`idnum`) VALUES (" . $this->_user['uid'] . ",'" . $realname . "','" . $mobile . "'," . $province_id . "," . $city_id . "," . $county_id . ",'" . $address . "'," . $is_default . ",'" . $idnum . "')";

                    $address_id = $this->sql($sql);
                    if ($address_id > 0) {
                        $code = 200;
                        if ($is_default == 1) {
                            //默认大于0  修改其它地址为非默认。
                            $sql = "UPDATE {$this->_prefix['primary']}member_address SET is_default=0 where uid={$this->_user['uid']}  and id!=" . $address_id;
                            $this->sql($sql);
                        }

                        // 判断是否套餐礼包操作
                        if ($da['level_money'] != "") {

                            $code = 403;
                            $tao  = $this->checkTao();

                            if ($tao['level_money'] == $da['level_money']) {

                                $info = $tao['level_money'] . "套餐" . $da['tao'];

                                $sql = "UPDATE {$this->_prefix['primary']}member_payinfo SET `tao_info`='" . $info . "',`tao_name`='" . $realname . "',`tao_mobile`='" . $mobile . "',`tao_province_id`=" . $province_id . ",`tao_city_id`=" . $city_id . ",`tao_county_id`=" . $county_id . ",`tao_address`='" . $address . "',`is_received`=1 WHERE `order_id`=" . $tao['order_id'];

                                $rcs = $this->sql($sql);
                                if ($rcs > 0) {
                                    $code = 200;
                                }
                            }
                        }

                    } else {
                        $code = 403;
                    }

                }
            }
        }

        return json_encode(array('code' => $code, 'address_id' => $address_id));
    }

    // 获取优惠券
    public function getCoupon($coupon_id = 0)
    {
        if ($coupon_id > 0) {
            $tsql = " AND `coupon_id`=" . intval($coupon_id);
        }

        $sql  = "SELECT * FROM {$this->_prefix['primary']}discount_coupon WHERE `uid`=" . $this->_user['uid'] . $tsql . " AND `status`=0 AND `expire_time`>" . $_SERVER['REQUEST_TIME'] . " ORDER BY `expire_time` DESC";
        $data = $this->sql($sql);

        if ($data) {
            foreach ($data as $r) {
                $new[$r['coupon_id']] = $r;
            }

            return $new;
        }
    }

    // 获取用户资金
    public function getBalance()
    {
        $sql = "SELECT * FROM {$this->_prefix['primary']}finance_balance WHERE `uid`=" . $this->_user['uid'];
        return $this->db->getrow($sql);
    }

    // 获取设置
    public function getSetting()
    {
        $sql     = "SELECT `setting` FROM {$this->_prefix['primary']}setting ORDER BY `setting_id` DESC LIMIT 1";
        $setting = $this->db->getone($sql);
        if ($setting != "") {
            return json_decode($setting, true);
        }

    }
    // 检查未领取的套餐
    public function checkTao()
    {
        $sql  = "SELECT `order_id`,`level_money` FROM {$this->_prefix['primary']}member_payinfo WHERE `uid`=" . $this->_user['uid'] . " AND `pay_status`=2 AND `is_received`=0 ORDER BY `order_id` ASC LIMIT 1";
        $data = $this->db->getrow($sql);
        if ($data) {
            return $data;
        }
    }

}
